import React from 'react';
import '../../Chat.css';

const List: React.FC<{
  loading: boolean;
  error: string;
  filteredUsers: Array<{
    _id: string;
    username: string;
    name: string;
    image: string;
    type: 'user' | 'group';
    isTop?: boolean; // 置顶标识
    data?:
      | {
          _id: string;
          username: string;
          image: string;
        }
      | {
          _id: string;
          name: string;
          members: Array<{
            _id: string;
            username: string;
            image: string;
          }>;
          createdBy: {
            _id: string;
            username: string;
            image: string;
          };
          createdAt: string;
        };
  }>;
  lastMessages: {
    [username: string]: {
      message: string;
      messageType: string;
      timestamp: Date;
    };
  };
  lastMessagesLoading: boolean;
  activeTab: string;
  onUserClick: (user: { _id: string; username: string; image: string }) => void;
  onGroupClick: (group: {
    _id: string;
    name: string;
    members: Array<{
      _id: string;
      username: string;
      image: string;
    }>;
    createdBy: {
      _id: string;
      username: string;
      image: string;
    };
    createdAt: string;
  }) => void;
  formatTime: (date: Date | string) => string;
}> = ({
  loading,
  error,
  filteredUsers,
  lastMessages,
  lastMessagesLoading,
  activeTab,
  onUserClick,
  onGroupClick,
  formatTime,
}) => {
  const renderLastMessage = (username: string) => {
    if (lastMessagesLoading) {
      return <div className="last-message">加载中...</div>;
    }

    const lastMsg = lastMessages[username];
    if (!lastMsg) {
      return '';
    }

    if (lastMsg.messageType === 'text') {
      const textContent = lastMsg.message;
      return textContent.length > 15
        ? textContent.substring(0, 15) + '...'
        : textContent;
    } else if (lastMsg.messageType === 'image') {
      return '【图片】';
    } else if (lastMsg.messageType === 'video') {
      return '【视频】';
    } else if (lastMsg.messageType === 'file') {
      try {
        const fileData = JSON.parse(lastMsg.message);
        return `📁 ${fileData.name || '文件'}`;
      } catch {
        return '【文件】';
      }
    } else if (lastMsg.messageType === 'location') {
      try {
        const locationData = JSON.parse(lastMsg.message);
        return `📍 ${locationData.address || '位置'}`;
      } catch {
        return '【位置】';
      }
    } else {
      return '点击开始聊天';
    }
  };

  if (loading) {
    return (
      <div className="users-list">
        <div className="loading">
          <div>加载中...</div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="users-list">
        <div className="error">
          <div>{error}</div>
          <button
            onClick={() => window.location.reload()}
            style={{
              marginTop: '10px',
              padding: '8px 16px',
              background: '#667eea',
              color: 'white',
              border: 'none',
              borderRadius: '20px',
              cursor: 'pointer',
            }}
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  if (filteredUsers.length === 0) {
    return (
      <div className="users-list">
        <div className="no-users">
          <div>暂无{activeTab === 'group' ? '群聊' : '用户'}</div>
        </div>
      </div>
    );
  }

  return (
    <div className="users-list">
      {filteredUsers.map(item => {
        return (
          <div
            key={item._id}
            className={`user-item ${item.isTop ? 'pinned-chat' : ''}`}
            style={{
              transition: 'background-color 0.2s ease',
            }}
            onClick={() => {
              if (item.type === 'user' && item.data) {
                onUserClick(
                  item.data as { _id: string; username: string; image: string }
                );
              } else if (item.type === 'group' && item.data) {
                onGroupClick(
                  item.data as {
                    _id: string;
                    name: string;
                    members: Array<{
                      _id: string;
                      username: string;
                      image: string;
                    }>;
                    createdBy: {
                      _id: string;
                      username: string;
                      image: string;
                    };
                    createdAt: string;
                  }
                );
              }
            }}
          >
            <div>
              <div>
                <img
                  src={item.image}
                  alt={item.name}
                  // className='user-avatar-img'
                  style={{
                    width: '40px',
                    height: '40px',
                    borderRadius: '20%',
                    marginRight: '30px',
                    marginBottom: '-10px',
                    marginLeft: '5px',
                    marginTop: '10px',
                  }}
                />
              </div>
              <div>
                <div
                  style={{
                    fontSize: '14px',
                    fontWeight: '600',
                    color: '#333',
                    minWidth: '80px',
                    textAlign: 'left',
                    // marginBottom: '-15px',
                    marginTop: '-30px',
                    marginLeft: '55px',
                    // backgroundColor: 'red',
                  }}
                >
                  {item.name}
                  {item.isTop && (
                    <span style={{ color: '#007aff', fontSize: '12px' }}>
                      📌
                    </span>
                  )}
                </div>
                <div
                  style={{
                    maxWidth: '180px',
                    minWidth: '130px',
                    fontSize: '12px',
                    color: '#999',
                    textAlign: 'left',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                    lineHeight: '1.4',
                    marginLeft: '50px',
                    marginRight: '-100px',
                    // backgroundColor: 'blue',
                  }}
                >
                  {renderLastMessage(item.username)}
                </div>
              </div>
            </div>
            <div className="message-time">
              {(() => {
                const lastMsg = lastMessages[item.username];
                if (lastMsg && lastMsg.timestamp) {
                  // 添加调试信息
                  console.warn(`用户 ${item.username} 的最后消息时间:`, {
                    timestamp: lastMsg.timestamp,
                    type: typeof lastMsg.timestamp,
                    parsed: new Date(lastMsg.timestamp),
                  });
                  return formatTime(lastMsg.timestamp);
                } else {
                  return '暂无消息';
                }
              })()}
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default List;
